package com.youkeda.test.http;


import com.alibaba.excel.EasyExcel;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class ExcelAsker {

    public static void main(String[] args) {
        String url = "https://style.youkeda.com/img/ham/course/py2/china-city-list.xlsx";
        ExcelAsker asker = new ExcelAsker();
        byte[] data = asker.getFile(url);
        try {
            File file = new File("china-city-list.xlsx");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data);
            fos.flush();
            fos.close();
            System.out.println("下载成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Map<Integer, String>> sheetDatas = EasyExcel.read("china-city-list.xlsx").sheet(0).doReadSync();
        for (Map<Integer, String> rowData : sheetDatas) {
            for (Integer index : rowData.keySet()) {
                System.out.print(rowData.get(index) + " ");
            }
            System.out.println();
        }

    }

    /**
     * 根据输入的url，读取页面内容并返回
     */
    public byte[] getFile(String url) {
        // okHttpClient 实例
        OkHttpClient okHttpClient = new OkHttpClient();
        // 定义一个request
        Request request = new Request.Builder().url(url).build();
        byte[] bytes = null;
        try {
            // 执行请求
            Response response = okHttpClient.newCall(request).execute();
            bytes = response.body().bytes();
        } catch (IOException e) {
            // 抓取异常
            System.out.println("request " + url + " error . ");
            e.printStackTrace();
        }

        return bytes;
    }
}
